import testSortCol.CollectionWithGet;
import datastructures.LinkedCollection;

/**
 * @author Daniel Bergqvist 900203-2432
 * @author Marika Hansson 910305-0804
 */
public class SortedLinkedCollection<E extends Comparable<? super E>> extends
		LinkedCollection<E> implements CollectionWithGet<E> {

	/**
	 * @param E
	 *            its a element of a generic type to search for in the
	 *            collection.
	 * @return the same element as parameter if its exist, null if it doesn't. .
	 */
	public E get(E e) {
		Entry temp = head;
		while (temp != null && e.compareTo(temp.element) > 0) {
			temp = temp.next;
		}
		if (temp != null && e.compareTo(temp.element) == 0) {
			return temp.element;
		}
		return null;
	}

	/**
	 * @param E
	 *            its the element of a generic type.
	 * @return true if the element is added in the collection.
	 */
	@Override
	public boolean add(E element) {
		if (element == null) {
			throw new NullPointerException("Can't add null!");
		} else if (isEmpty()) {
			head = new Entry(element, null);
		} else if (element.compareTo(head.element) <= 0) {
			head = new Entry(element, head);
		} else {
			Entry temp = head;
			while (temp.next != null) {
				if (element.compareTo(temp.next.element) <= 0) {
					break;
				}
				temp = temp.next;
			}
			if (temp.next == null) {
				temp.next = new Entry(element, null);
			} else {
				temp.next = new Entry(element, temp.next);
			}
		}
		return true;
	}
}
